#!/bin/bash

# 脚本功能：发布插件到JetBrains Marketplace

echo "发布插件到JetBrains Marketplace"
echo "================================"

# 检查是否设置了JETBRAINS_TOKEN环境变量
if [ -z "$JETBRAINS_TOKEN" ]; then
    echo "错误：未设置JETBRAINS_TOKEN环境变量"
    echo "请先设置JETBRAINS_TOKEN环境变量："
    echo "  export JETBRAINS_TOKEN=您的令牌"
    echo ""
    echo "获取令牌的方法："
    echo "1. 登录到 https://plugins.jetbrains.com/"
    echo "2. 转到 https://plugins.jetbrains.com/author/me/tokens"
    echo "3. 点击 'Generate Token' 创建新令牌"
    exit 1
fi

# 检查是否有其他IDEA实例在运行
echo "检查是否有其他IDEA实例在运行..."
if pgrep -f "IntelliJ IDEA" > /dev/null; then
    echo "检测到正在运行的IDEA实例"
    echo "这可能会干扰发布过程，建议在发布前关闭所有IDEA实例"
    echo ""
    echo "选项："
    echo "1. 继续发布（可能会失败）"
    echo "2. 终止现有实例并继续发布"
    echo "3. 取消发布"
    
    read -p "请选择操作 [1/2/3]: " choice
    
    case $choice in
        1)
            echo "继续发布..."
            ;;
        2)
            echo "终止现有IDEA实例..."
            pkill -f "IntelliJ IDEA"
            sleep 3
            ;;
        *)
            echo "取消发布"
            exit 0
            ;;
    esac
fi

echo ""
echo "开始构建和发布插件..."
echo "这可能需要几分钟时间..."

# 执行发布命令
./gradlew publishPlugin

# 检查发布结果
if [ $? -eq 0 ]; then
    echo ""
    echo "插件发布成功！"
    echo "请访问 https://plugins.jetbrains.com/ 检查您的插件状态"
else
    echo ""
    echo "插件发布失败！"
    echo "请检查错误信息并重试"
    exit 1
fi